package com.java.es.pojo;

/**
 * @author jiangli
 * @date 2019/11/18 22:23
 * synchronized版
 */
public class ThreadNotifyDemo {

	public static void main(String[] args) {
		Res res = new Res();
		Input input = new Input(res);
		Output output = new Output(res);
		input.start();
		output.start();
	}
}

class Input extends Thread {
	private Res res;

	public Input(Res res) {
		this.res = res;
	}

	@Override
	public void run() {
		int count = 0;
		while (true) {
			synchronized (res) {
				if (res.flag) {
					try {
						res.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				if (count == 0) {
					res.name = "杨过";
					res.sex = "男";
				} else {
					res.name = "小龙女";
					res.sex = "女";
				}
				count = (count + 1) % 2;
				res.flag = true;
				res.notify();
			}
		}

	}
}

class Output extends Thread {
	private Res res;

	public Output(Res res) {
		this.res = res;
	}

	@Override
	public void run() {
		while (true) {
			synchronized (res) {
				if (!res.flag) {
					try {
						res.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				System.out.println("名字:" + res.name + ", 性别:" + res.sex);
				res.flag = false;
				res.notify();
			}
		}
	}
}

class Res {
	public String name;
	public String sex;
	// flag false out线程未读取值
	public boolean flag = false;

}